package sieve

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/wire"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"sieve_admin_server_userpass/app/schema"
	"sieve_admin_server_userpass/lib/config"
)

var (
	SieveEngineSet = wire.NewSet(wire.Struct(new(SieveEngineSrv), "*"))

	sieveEngineUrl = *config.String("sieve.internal_v3.url", "http://198.200.54.86:9810", "sieve engine address")
)

type SieveEngineSrv struct {
}

func (a *SieveEngineSrv) Query(ctx context.Context, reqArgs map[string]interface{}, p schema.PaginationParam) interface{} {

	var (
		method    = "GET"
		client    = &http.Client{}
		parameter = url.Values{
			"state":      {fmt.Sprintf("%v", reqArgs["state"])},
			"detail":     {fmt.Sprintf("%v", reqArgs["detail"])},
			"page_index": {fmt.Sprintf("%v", p.PageIndex)},
			"page_size":  {fmt.Sprintf("%v", p.PageSize)},
		}
		requestURL = fmt.Sprintf("%v/api/task?%v", sieveEngineUrl, parameter.Encode())
	)

	req, err := http.NewRequest(method, requestURL, nil)
	if err != nil {
		fmt.Println(err)
		return err
	}

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return err
	}

	return json.RawMessage(body)
}

func (a *SieveEngineSrv) Operate(ctx context.Context, reqArgs map[string]interface{}) interface{} {

	var (
		method     = "POST"
		client     = &http.Client{}
		requestURL = fmt.Sprintf("%v/api/task.control", sieveEngineUrl)
	)

	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)

	_ = writer.WriteField("op", fmt.Sprintf("%v", reqArgs["op"]))

	if reqArgs["op"] == "prioritise" {
		_ = writer.WriteField("from_task_id", fmt.Sprintf("%v", reqArgs["from_task_id"]))
		_ = writer.WriteField("to_task_id", fmt.Sprintf("%v", reqArgs["to_task_id"]))
		_ = writer.WriteField("before_or_after", fmt.Sprintf("%v", reqArgs["before_or_after"]))
	}

	if reqArgs["op"] == "pause" || reqArgs["op"] == "start" || reqArgs["op"] == "terminal" {
		_ = writer.WriteField("task_id", fmt.Sprintf("%v", reqArgs["task_id"]))
	}
	_ = writer.Close()
	req, err := http.NewRequest(method, requestURL, payload)
	if err != nil {
		fmt.Println(err)
		return err
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println(string(body))

	respMap := make(map[string]interface{})
	err = json.Unmarshal(body, &respMap)
	if err != nil {
		return err
	}
	return respMap
}
